package validated

import (
	"errors"
	"reflect"

	CN_ZH "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var validate *validator.Validate

// Validate/v10 全局验证器
var trans ut.Translator

func init() {
	zh := CN_ZH.New()
	uni := ut.New(zh, zh)
	trans, _ = uni.GetTranslator("zh")

	validate = validator.New()

	//通过label标签返回自定义错误内容
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		label := field.Tag.Get("label")
		if label == "" {
			return field.Name
		}
		return label
	})

	zh_translations.RegisterDefaultTranslations(validate, trans)
	//自定义required_if错误内容
	validate.RegisterTranslation("required_if", trans, func(ut ut.Translator) error {
		return ut.Add("required_if", "{0}为必填字段!", false) // see universal-translator for details
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("required_if", fe.Field())
		return t
	})
}

func ValidateStruct(obj any) error {
	err := validate.Struct(obj)
	if err != nil {
		errs := err.(validator.ValidationErrors)
		return errors.New(errs[0].Translate(trans))
	}
	return nil
}
